﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RR;


/// <summary>
/// Сводное описание для MainMenu
/// </summary>
public class MainMenu : IDisposable
{
    private RegistRar context = new RegistRar();

    public MainMenu()
    {
        //
        // TODO: добавьте логику конструктора
        //
    }

    public void BuildMenu(DevExpress.Web.ASPxMenu.ASPxMenu menu, int roleId)
    {
        //bool dispEnable = su.isDispEnable;
        var query = (from m in context.MENU
                     join mr in context.MENURIGHT on m.ID equals mr.MENUID
                     where mr.WORKERSTATE == roleId
                     select m).SortBy("ParentID");
        //if (Profile.UserInfo.disp.Kontragent == -1)
        //{ query = query.Where(a => a.ID != 12); }


        // Build Menu Items
        Dictionary<string, DevExpress.Web.ASPxMenu.MenuItem> menuItems =
            new Dictionary<string, DevExpress.Web.ASPxMenu.MenuItem>();

        foreach (var r in query)
        {
            DevExpress.Web.ASPxMenu.MenuItem item = CreateMenuItem(r);
            string itemID = r.ID.ToString();
            string parentID = r.PARENTID.ToString();
            string target = r.TARGET;
           

            if (menuItems.ContainsKey(parentID))
                menuItems[parentID].Items.Add(item);
            else
            {
                if (parentID == "0") // It's Root Item
                    menu.Items.Add(item);
            }
            menuItems.Add(itemID, item);
        }
    }

    private DevExpress.Web.ASPxMenu.MenuItem CreateMenuItem(MENU row)
    {
        DevExpress.Web.ASPxMenu.MenuItem ret = new DevExpress.Web.ASPxMenu.MenuItem();
        ret.Text = row.TEXT;
        ret.NavigateUrl = row.NAVIGATEURL;
        ret.Target = row.TARGET;
        return ret;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            if (context != null)
            {
                context.Dispose();
                context = null;
            }
    }
    ~MainMenu()
    {
        Dispose(false);
    }
}